<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/29
 * Time: 10:34
 */

namespace app\service\traits;

use app\admin\model\Company;
use app\company\model\Supplier;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Response;

trait LoginTrait
{
    use Menu;

    /**
     * 登录 此处对验证码进行了格外的处理1
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene("login")->check($param);

        //验证码
        if (!env('APP_DEBUG', false) && $this->isCheckCode) {
//            if (!captcha_check($param['code'], $param['code_id'])) return $this->error("验证码错误");
        }

        $info = $this->model->where('user_name', $param['user_name'])->find();
        if (!$info) return $this->error("用户不存在");
        if (md5(request()->param("password") . 'dt') != $info->password) return $this->error("用户或密码错误");
        $userInfo = $info->toArray();
        unset($userInfo['password']);
        $token = getToken($info->id, 1); // 生成JWT令牌
        //是否返回公司信息
        if ($this->isReturnCompany) {
            $userInfo['company'] = Company::where('id', $info->company_id)->field('id,name,cooperation_mode,service_charge,location,logo')->find();
        }
        if ($this->isReturnSupplier) {
            $userInfo['supplier'] = Supplier::where('id', $info->supplier_id)->field('id,name,cooperation_mode,service_charge')->find();
        }
        //是否返回权限
        if ($this->isReturnAuth) {
            $userInfo['auth'] = $this->getUserAuth($info);
        }

        return $this->success('成功', compact("userInfo", "token"));
    }

    /**
     * 获取验证码
     * @return Response
     */
    public function captcha(): Response
    {
        $id = uniqid((string)mt_rand(100000, 999999));
        return $this->success('成功', [
            'code'    => request()->domain() . captcha_src($id),
            'code_id' => $id
        ]);
    }
}